import { defineStore } from "pinia"
import { ref, computed } from "vue"
import { getWxOpenId, getAppUserInfo } from "@/api"
const initState = {}
export const useUserStore = defineStore(
  "user",
  () => {
    const userInfo = ref<any>({ ...initState })
    const token =ref<string>(null)
    const appid = "wx5d9163b7af511b7a" // 你的appid
    const setUserInfo = (val: any) => {
      userInfo.value = val
    }
    const setToken = (val: any) => {
      token.value = val
    }
    const clearUserInfo = () => {
      token.value = null
      userInfo.value = { ...initState }
    }
    const reset = () => {
      userInfo.value = { ...initState }
    }
    const isLogined = computed(() => !!token.value)
    const hasToken = computed(() => !!token.value)

    /**
     * 获取用户信息
     */
    const fetchUserInfo = async () => {
      try {
        const userInfoRes:any = await getAppUserInfo({})
        if (userInfoRes.success) {
          setUserInfo(userInfoRes.data)
          return userInfoRes.data
        } else {
          throw new Error(userInfoRes.msg || '获取用户信息失败')
        }
      } catch (error) {
        console.error('获取用户信息失败:', error)
        throw error
      }
    }

    /**
     * 微信登录
     */
    const loginByWechat = (phoneCode: string) => {
      return new Promise((resolve, reject) => {
        uni.login({
          provider: "weixin",
          success: async (res) => {
            try {
              const loginRes = await getWxOpenId({
                appid,
                loginCode: res.code,
                telephoneCode: phoneCode,
              })
              if (loginRes.success) {
                // 微信登录成功后设置token并获取用户信息
                const loginToken = loginRes.data
                setToken(loginToken)
                await fetchUserInfo()
                resolve(loginRes)
              } else {
                reject(loginRes)
              }
            } catch (error) {
              reject(error)
            }
          },
          error: (error) => {
            reject(error)
          },
        })
      })
    }
    return {
      userInfo,
      setUserInfo,
      clearUserInfo,
      isLogined,
      hasToken,
      reset,
      appid,
      loginByWechat,
      fetchUserInfo,
      token,
      setToken
    }
  },
  {
    persist: true,
  },
)
